package org.shock.ss.sms.dao;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.shock.ss.sms.commons.db.ProxoolDbPool;

public class AutoTextDao {
	private String hh = "\r\n";// 换行用字符串

	/**
	 * 根据表名获得表结构
	 * 
	 * @param tablename
	 *            表名
	 * @return list 存储的表结构
	 * @throws Exception
	 */
	public List<Map<String, String>> getTableInfo(String tablename) throws Exception {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String sql = "select A.column_name columnname,A.data_type type,'' length,"
				+ "'' zs,'' xs,A.is_nullable nullable,A.column_default defaultvalue,"
				+ "A.column_comment bz from information_schema.columns A where" + " A.Table_Name='"
				+ tablename.toUpperCase() + "'";
		try {
			conn = ProxoolDbPool.getConnection();
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while (rs.next()) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("columnname", objToString(rs.getString("columnname")));
				map.put("type", objToString(rs.getString("type")));
				map.put("length", objToString(rs.getString("length")));
				map.put("zs", objToString(rs.getString("zs")));
				map.put("xs", objToString(rs.getString("xs")));
				map.put("nullable", objToString(rs.getString("nullable")));
				map.put("defaultvalue", objToString(rs.getString("defaultvalue")));
				map.put("bz", objToString(rs.getString("bz")));
				list.add(map);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			ProxoolDbPool.closeConnection(conn);
			ProxoolDbPool.closeResultSet(rs);
			ProxoolDbPool.closeStatement(stmt);
		}
		return list;
	}

	/**
	 * 根据表结构list组合Bean类的代码(***季乐有更好的方法，暂不处理***)
	 * 
	 * @param list
	 *            表结构list
	 * @return beanString Bean类的代码
	 */
	public String getBeanPage(List<Map<String, String>> list, String tablename) {
		String beanString = "";
		beanString += "" + "package org.shock.ss.sms.bean." + tablename.toLowerCase() + ";" + hh + "import java.io.Serializable;"
				+ hh + "public class " + toUpperHead(tablename) + " implements Serializable {" + hh
				+ "	@SuppressWarnings(\"unused\")" + hh + "	private static final long serialVersionUID = 1L;" + hh
				+ "	private static final String table = \"" + tablename.toLowerCase() + "\";// 数据库表名\";";
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> map = list.get(i);// 获得字段属性map
			beanString += "" + hh + "	/**" + objToString(map.get("bz")) + "*/" + hh + "	private " + checkDataType(map)
					+ " " + objToString(map.get("columnname")).toLowerCase() + " " + getDataValue(map) + ";";
		}
		beanString += "" + hh + "}	";
		return beanString;
	}

	/**
	 * 根据传来的字段属性map判断字段的类型
	 * 
	 * @param map
	 *            字段属性map，详情请参加自动生成代码的获取表结构list方法
	 * @return type 字段的类型
	 */
	public String checkDataType(Map<String, String> map) {
		String type = objToString(map.get("type")).toLowerCase();
		if ("".equals(type)) {
			return "String";
		} else if (type.toLowerCase().contains("bigint")) {
			if (objToString(map.get("columnname")).toLowerCase().contains("id")) {
				return "Long";
			} else {
				return "Integer";
			}
		} else if (type.toLowerCase().contains("int")) {
			return "Integer";
		} else if ("date".equals(type)) {
			return "Date";
		} else {
			return "String";
		}
	}

	/**
	 * 根据传来的字段属性map判断字段的默认值
	 * 
	 * @param map
	 *            字段属性map，详情请参加自动生成代码的获取表结构list方法
	 * @return type 字段的类型
	 */
	public String getDataValue(Map<String, String> map) {
		String value = "";
		if (null == map.get("defaultvalue") || "".equals(objToString(map.get("defaultvalue")))) {

		} else if (objToString(map.get("defaultvalue")).replaceAll(" ", "").length() > 0) {
			value = "= " + map.get("defaultvalue");
		}
		return value;
	}

	/**
	 * 通过表结构list组合添加页面的代码
	 * 
	 * @param list
	 *            表结构list
	 * @return addpageString 返回的添加页面的代码
	 */
	public String getAddPage(List<Map<String, String>> list) {
		String addpageString = "";
		addpageString += "" + hh + "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"" + hh
				+ "pageEncoding=\"UTF-8\"%>" + hh + "<%@ taglib prefix=\"s\" uri=\"/struts-tags\"%>" + hh + "<%" + hh
				+ "	String path = request.getContextPath();" + hh + "	String basePath = request.getScheme() + \"://\""
				+ hh + "			+ request.getServerName() + \":\" + request.getServerPort()" + hh + "			+ path + \"/\";"
				+ hh + "%>" + hh + "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">" + hh + "<html>"
				+ hh + "	<head>" + hh + "		<title></title>" + hh + "		<!-- 全局css引入 必须 -->" + hh
				+ "		<link href=\"<%=basePath%>/style/style.css\" rel=\"stylesheet\" type=\"text/css\">" + hh
				+ "		<link href=\"<%=basePath%>/style/global.css\" rel=\"stylesheet\" type=\"text/css\">" + hh
				+ "		<!-- 结束 -->" + hh +
				/* " <!-- 表单专用css 必须引入-->"+hh+ */
				"		<!-- 用到表单验证必须引入 -->" + hh + "		<jsp:include page=\"/vailidateInclude.jsp\" />" + hh
				+ "		<!-- 结束 -->" + hh + "		<!--如用到ext必须引入 -->" + hh + "		<jsp:include page=\"/extInclude.jsp\" />"
				+ hh + "		<!-- 结束 -->" + hh + "		<!-- 日期控件开始 -->" + hh
				+ "		<script type=\"text/javascript\" src=\"<%=basePath%>/js/DatePicker/WdatePicker.js\"></script>"
				+ hh + "		<!-- 日期控件结束 -->" + hh + "		<!-- 模块选择js -->" + hh
				+ "		<script src=\"<%=basePath%>/js/selector/ModuleSelector.js\" type=\"text/javascript\"></script>"
				+ hh + "	</head>" + hh + "	<body>" + hh +

				"	<div class=\"rightCon\" align=\"center\">" + hh + "	 	<div class=\"rightTitle2\">" + hh + "			<h3>"
				+ hh + "				<s:property value=\"nav\" escape=\"false\"/>" + hh + "			</h3>" + hh + "	</div>" + hh
				+ "		<s:form action=\"XXX.do\" method=\"post\" cssClass=\"\">" + hh + "			<table class=\"formTable\">"
				+ hh + "			<colgroup>" + hh + "				<col align=\"right\" class=\"formLabel\"/>" + hh
				+ "				<col align=\"left\" />" + hh + "				<col align=\"right\" class=\"formLabel\"/>" + hh
				+ "				<col align=\"left\" />" + hh + "			</colgroup>" + hh;
		// 开始循环表的字段
		int listsize = list.size();
		for (int i = 0; i < listsize; i++) {
			Map<String, String> map = list.get(i);
			String zdname1 = objToString(map.get("columnname")).toLowerCase();// 字段名称1
			String beizhu1 = objToString(map.get("bz"));// 备注1
			String zdname2 = "";// 字段名称2
			String beizhu2 = "";// 备注2
			if (i < listsize - 1) {
				i++;
				map = list.get(i);
				zdname2 = objToString(map.get("columnname")).toLowerCase();
				beizhu2 = objToString(map.get("bz"));
			}
			addpageString += "" + "				<tr>" + hh + "					<td" + (i == 1 ? " width=\"20%\"" : "") + ">" + hh + "						"
					+ (beizhu1.length() > 7 ? beizhu1.substring(0, 5) : beizhu1) + "：" + hh + "						<!-- " + zdname1
					+ " -->" + hh + "					</td>" + hh + "					<td" + (i == 1 ? " width=\"30%\"" : "") + ">" + hh
					+ "						<s:textfield name=\"map." + zdname1.toLowerCase() + "\" id=\"" + zdname1.toLowerCase()
					+ "\" cssClass=\"required\"></s:textfield>" + hh + "					</td>" + hh + "					<td"
					+ (i == 1 ? " width=\"20%\"" : "") + ">" + hh + "						"
					+ (beizhu2.length() > 7 ? beizhu2.substring(0, 5) : beizhu2) + "：" + hh + "						<!-- " + zdname2
					+ " -->" + hh + "					</td>" + hh + "					<td" + (i == 1 ? " width=\"30%\"" : "") + ">" + hh
					+ "						<s:textfield name=\"map." + zdname2.toLowerCase() + "\" id=\"" + zdname2.toLowerCase()
					+ "\" cssClass=\"required\"></s:textfield>" + hh + "					</td>" + hh + "				</tr>" + hh;
		}
		addpageString += "" + "			</table>" + hh + "			<table  class=\"form_submit_bar\">" + hh + "				<tr>" + hh
				+ "					<td width=\"30%\" align=\"center\" colspan=\"4\">" + hh
				+ "						<input class=\"buttonOk\" id=\"button2\" type=\"submit\" value=\"保存\" />" + hh
				+ "						&nbsp;&nbsp;&nbsp;&nbsp;" + hh
				+ "						<input class=\"buttonOk\" id=\"button2\" type=\"reset\" value=\"重置\" />" + hh + "					</td>"
				+ hh + "				</tr>" + hh + "			</table>" + hh + "		</s:form>" + hh + "	</body>" + hh + "</html>";

		return addpageString;
	}

	/**
	 * 根据表结构list组合查看页面的代码
	 * 
	 * @param list
	 *            表结构list
	 * @return viewString 查看页面的代码
	 */
	public String getViewPage(List<Map<String, String>> list) {
		String viewString = "";
		viewString += "" + "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"" + hh
				+ "	pageEncoding=\"UTF-8\"%>" + hh + "<%@ taglib prefix=\"s\" uri=\"/struts-tags\"%>" + hh + "<%" + hh
				+ "	String path = request.getContextPath();" + hh + "	String basePath = request.getScheme() + \"://\""
				+ hh + "			+ request.getServerName() + \":\" + request.getServerPort()" + hh + "			+ path + \"/\";"
				+ hh + "%>" + hh + "<!-- 全局css引入 必须 -->" + hh
				+ "<link href=\"<%=basePath%>/style/style.css\" rel=\"stylesheet\" type=\"text/css\">" + hh
				+ "<link href=\"<%=basePath%>/style/global.css\" rel=\"stylesheet\" type=\"text/css\">" + hh
				+ "<script type=\"text/javascript\" src=\"<%=basePath%>/js/global.js\"></script>" + hh + "<!-- 结束 -->"
				+ hh + "<div class=\"rightCon\" align=\"center\">" + hh + "	<div class=\"rightTitle2\">" + hh
				+ "		<h3>" + hh + "			<s:property value=\"nav\"/>" + hh + "		</h3>" + hh + "	</div>" + hh
				+ "	<table class=\"formTable\">" + hh + "			<colgroup>" + hh
				+ "				<col align=\"right\" class=\"formLabel\"/>" + hh + "				<col align=\"left\" />" + hh
				+ "				<col align=\"right\" class=\"formLabel\"/>" + hh + "				<col align=\"left\" />" + hh
				+ "			</colgroup>" + hh;
		// 开始循环表的字段
		int listsize = list.size();
		for (int i = 0; i < listsize; i++) {
			Map<String, String> map = list.get(i);
			String zdname1 = objToString(map.get("columnname")).toLowerCase();// 字段名称1
			String beizhu1 = objToString(map.get("bz"));// 备注1
			String zdname2 = "";// 字段名称2
			String beizhu2 = "";// 备注2
			if (i < listsize - 1) {
				i++;
				map = list.get(i);
				zdname2 = objToString(map.get("columnname")).toLowerCase();
				beizhu2 = objToString(map.get("bz"));
			}

			viewString += "" + "		<tr>" + hh + "			<td" + (i == 1 ? " width=\"50%\"" : "") + ">" + hh + "				"
					+ beizhu1 + "：" + hh + "				<!-- " + zdname1 + "  -->" + hh + "			</td>" + hh + "			<td"
					+ (i == 1 ? " width=\"50%\"" : "") + ">" + hh + "				<s:property value=\"map." + zdname1 + "\"/>"
					+ hh + "			</td>" + hh + "			<td" + (i == 1 ? " width=\"50%\"" : "") + ">" + hh + "				" + beizhu2
					+ "：" + hh + "				<!-- " + zdname2 + "  -->" + hh + "			</td>" + hh + "			<td"
					+ (i == 1 ? " width=\"50%\"" : "") + ">" + hh + "				<s:property value=\"map." + zdname2 + "\"/>"
					+ hh + "			</td>" + hh + "		</tr>" + hh;

		}
		viewString += "" + "	</table>" + hh + "	<table class=\"form_submit_bar\">" + hh + "		<tr>" + hh + "			<td>"
				+ hh + "				<input onclick=\"history.go(-1)\" class=\"buttonReturn\" id=\"button2\" type=\"button\""
				+ hh + "					value=\"返回\" />" + hh + "			</td>" + hh + "		</tr>" + hh + "	</table>" + hh + "</div>";

		return viewString;
	}

	/**
	 * 根据表结构list组合列表分页页面的代码
	 * 
	 * @param list
	 *            表结构文档
	 * @return listPageString 列表分页页面的代码
	 */
	public String getListPage(List<Map<String, String>> list) {
		String listPageString = "";
		listPageString += "" + "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"" + hh
				+ "pageEncoding=\"UTF-8\"%>" + hh + "<%@ taglib prefix=\"s\" uri=\"/struts-tags\"%>" + hh + "<%" + hh
				+ "	String path = request.getContextPath();" + hh + "	String basePath = request.getScheme() + \"://\""
				+ hh + "			+ request.getServerName() + \":\" + request.getServerPort()" + hh + "			+ path + \"/\";"
				+ hh + "%>" + hh + "<!--如用到jqueryBox必须引入 -->" + hh + "<jsp:include page=\"/jqueryInclude.jsp\" />" + hh
				+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">" + hh + "<html>" + hh + "	<head>"
				+ hh + "		<title></title>" + hh + "		<link href=\"<%=basePath%>/style/style.css\" rel=\"stylesheet\">"
				+ hh + "		<link href=\"<%=basePath%>/style/global.css\" rel=\"stylesheet\" type=\"text/css\">" + hh
				+ "	</head>" + hh + "	<body>" + hh + "	<div class=\"rightCon\" align=\"center\">" + hh
				+ "		<div class=\"rightTitle\" align=\"left\">" + hh + "			<h3>" + hh
				+ "				<s:property value=\"nav\"/>" + hh + "			</h3>" + hh + "		</div>" + hh +

				"		<table class=\"listTable\">" + hh + "				<tr class=\"listTitle\">" + hh
				+ "					<td width=\"10%\" class=\"title2\">" + hh + "						序号" + hh + "					</td>" + hh;
		// 开始循环表的字段
		int listsize = list.size();
		for (int i = 0; i < listsize; i++) {
			Map<String, String> map = list.get(i);
			String zdname1 = map.get("columnname");// 字段名称1
			String beizhu1 = map.get("bz");// 备注1
			listPageString += "" + "					<td width=\"10%\" class=\"title2\">" + hh + "						"
					+ (beizhu1.length() > 4 ? beizhu1.substring(0, 3) : beizhu1) + "" + hh + "						<!-- " + zdname1
					+ " -->" + hh + "					</td>" + hh;
		}
		listPageString += "" + "					<td width=\"21%\"  class=\"title2\">" + hh + "						操作" + hh + "					</td>" + hh
				+ "				</tr>" + hh + "				<s:iterator id=\"f\" value=\"%{list}\" status=\"stuts\">" + hh
				+ "				<tr  class=\"listTr\">" + hh + "					<td>" + hh + "						<s:property value=\"#stuts.count\" />"
				+ hh + "					</td>" + hh;

		// 开始循环表的字段
		for (int i = 0; i < listsize; i++) {
			Map<String, String> map = list.get(i);
			String zdname1 = map.get("columnname");// 字段名称1
			String beizhu1 = map.get("bz");// 备注1
			listPageString += "" + "					<td>" + hh + "						<s:property value=\"#f." + zdname1.toLowerCase() + "\" />"
					+ hh + "						<!-- " + beizhu1 + " -->" + hh + "					</td>" + hh;
		}
		listPageString += "" + "					<td>"
				+ hh
				+ "						<img src=\"images/btn/look.gif\" />"
				+ hh
				+ "						<a href=\"XXX.do?id=<s:property value=\"#f.id\"/>\">[查看]</a>"
				+ hh
				+

				"						<img src=\"images/system/edit.gif\" />"
				+ hh
				+ "						<a"
				+ hh
				+ "							href=\"XXX.do?action=before&id=<s:property value=\"#f.id\"/>\">[修改]</a>"
				+ hh
				+ "						<img src=\"images/pic27.gif\" />"
				+ hh
				+ "						<a"
				+ hh
				+ "							href=\"javascript:if(confirm('您真的要删除吗?点击确认进行删除！否则请点取消'))window.location=window.location;\">[删除]</a>"
				+ hh
				+ "					</td>"
				+ hh
				+ "				</tr>"
				+ hh
				+ "				</s:iterator>"
				+ hh
				+ "			</table>"
				+ hh
				+ "			<table width=\"92%\" border=\"0\" align=\"center\" cellpadding=\"0\""
				+ hh
				+ "				cellspacing=\"0\">"
				+ hh
				+ "				<tr>"
				+ hh
				+ "					<td width=\"52%\" height=\"38\">"
				+ hh
				+ "						<a href=\"addXXXX.do?action=before\" class=\"search button01\">添加</a>"
				+ hh
				+ "						<a"
				+ hh
				+ "							onclick=\"jBox.open('div-jBoxID','div','search1','按条件查询','width=700,height=160,center=true,minimizable=true,resize=false,draggable=true,model=false');\""
				+ hh + "							href=\"javascript://\" class=\"search button01\">查询</a>" + hh + "					</td>" + hh
				+ "					<td width=\"48%\" align=\"right\">" + hh
				+ "						<span style=\"text-align: center\"><s:property value=\"pageStr\"  escape=\"false\"/></span>"
				+ hh + "					</td>" + hh + "				</tr>" + hh + "			</table>" + hh + "		</div>" + hh +

				"		<div id=\"search1\" style=\"display: none;\">" + hh + "			<form method=\"post\" action=\"\">" + hh
				+ "				<table  class=\"searchTable\">" + hh + "					<tr>" + hh
				+ "						<td width=\"20%\" align=\"right\" height=\"30\">" + hh + "							XXXXX：" + hh + "						</td>"
				+ hh + "						<td width=\"20%\" align=\"left\">" + hh
				+ "							<input type=\"text\" name=\"\" title=\"XXXXX\">" + hh + "						</td>" + hh
				+ "						<td width=\"20%\" align=\"right\">" + hh + "							XXXXX：" + hh + "						</td>" + hh
				+ "						<td width=\"40%\" align=\"left\">" + hh
				+ "							<input type=\"text\" name=\"\" title=\"XXXXX\">" + hh + "						</td>" + hh + "					</tr>"
				+ hh + "					<tr>" + hh + "						<td width=\"30%\" align=\"center\" colspan=\"4\" class=\"maintb1\">"
				+ hh + "							<center>" + hh + "								<input id=\"button2\" type=\"submit\" value=\"搜索\" />" + hh
				+ "								&nbsp;&nbsp;&nbsp;&nbsp;" + hh
				+ "								<input id=\"button2\" type=\"reset\" value=\"重置\" />" + hh + "							</center>" + hh
				+ "						</td>" + hh + "					</tr>" + hh + "				</table>" + hh + "			</form>" + hh + "		</div>" + hh
				+ "	</body>" + hh + "</html>";
		return listPageString;
	}

	/**
	 * 根据表名tablename组合service接口文件
	 * 
	 * @param tablename
	 * @return
	 */
	public String getIServicePage(String tablename) {
		String IserviceString = "";
		IserviceString += "" + "package org.shock.ss.sms.service." + tablename.toLowerCase() + ";" + hh
				+ "import org.shock.ss.sms.commons.service.BaseService;" + hh + "public interface " + toUpperHead(tablename)
				+ "Service extends BaseService {" + hh + "	" + hh + "}";
		return IserviceString;
	}

	/**
	 * 根据表名生成相应的service类文件
	 * 
	 * @param tablename
	 * @return
	 */
	public String getServicePage(String tablename) {
		String serviceString = "";
		serviceString += "" + "package org.shock.ss.sms.service." + tablename.toLowerCase() + ".impl;" + hh
				+ "import org.shock.ss.sms.commons.dao.BaseDao;" + hh + "import org.shock.ss.sms.commons.service.impl.BaseServiceImpl;"
				+ hh + "import org.shock.ss.sms.service." + tablename.toLowerCase() + "." + toUpperHead(tablename) + "Service;"
				+ hh + "public class " + toUpperHead(tablename) + "ServiceImpl extends BaseServiceImpl implements "
				+ toUpperHead(tablename) + "Service {" + hh + "	public " + toUpperHead(tablename)
				+ "ServiceImpl(BaseDao dao) {" + hh + "		super(dao);" + hh + "	}" + hh + "}";
		return serviceString;
	}

	/**
	 * 根据表名创建dao接口文件
	 * 
	 * @param tablename
	 * @return
	 */
	public String getIDaoPage(String tablename) {
		String IDaoString = "";
		IDaoString += "" + "package org.shock.ss.sms.dao." + tablename.toLowerCase() + ";" + hh
				+ "import org.shock.ss.sms.commons.dao.BaseDao;" + hh + "public interface " + toUpperHead(tablename)
				+ "Dao extends BaseDao {" + hh + "	" + hh + "}";

		return IDaoString;
	}

	/**
	 * 根据表名组合dao类代码
	 * 
	 * @param tablename
	 * @return
	 */
	public String getDaoPage(String tablename) {
		String DaoString = "";
		DaoString += "" + "package org.shock.ss.sms.dao." + tablename.toLowerCase() + ".impl;" + hh
				+ "import org.shock.ss.sms.commons.dao.impl.BaseDaoImpl;" + hh + "import org.shock.ss.sms.dao." + tablename.toLowerCase()
				+ "." + toUpperHead(tablename) + "Dao;" + hh + "public class " + toUpperHead(tablename)
				+ "DaoImpl extends BaseDaoImpl implements " + toUpperHead(tablename) + "Dao {" + hh + "	" + hh + "}";

		return DaoString;
	}

	/**
	 * 将object的转化为String
	 * 
	 * @param obj
	 * @return
	 */
	public String objToString(Object obj) {
		String value = "";
		value = null == obj ? "" : obj.toString().trim();

		return value;
	}

	/**
	 * 创建文件
	 * 
	 * @param filename
	 *            文件名，包括路径地址，如："e:\\自动生成代码\\123\\456.txt"
	 * @param text
	 *            文件内容
	 */
	public void makeFile(String filename, String text) {
		RandomAccessFile rom = null;
		File file = new File(filename);
		file.getParentFile().mkdirs();
		try {
			file.createNewFile();
			rom = new RandomAccessFile(file, "rw");
			rom.write(text.getBytes());
			rom.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("已经存储文件至：" + filename);
		System.out.println("请注意查收，谢谢使用！");
	}

	/**
	 * 将首字母大写
	 * 
	 * @param word
	 *            将要处理的字符串
	 * @return
	 */
	public String toUpperHead(String word) {
		if (null != word && !"".equals(word) && word.length() > 0) {
			word = word.substring(0, 1).toUpperCase() + word.substring(1, word.length()).toLowerCase();
		} else {
			word = "";
		}
		return word;
	}

}
